'use client';

import type {
  ICreateChildReplyBody,
  IPostClientDetails,
  IPostComment,
  IPostCommentChildReply,
  IPostCommentParentReply,
  IPostCommentReply,
} from '@/interfaces';
import type { TBody, TMetadata } from '@/types';
import useUser from '@/hooks/useUser';
import { type ChangeEvent, useState } from 'react';
import {
  type UseInfiniteQueryResult,
  useMutation,
} from '@tanstack/react-query';
import useToast, { LoginReminderContent } from '@/hooks/useToast';
import { createChildReply } from '@/services/api';
import sanitizeHtml from 'sanitize-html';
import Image from 'next/image';
import { getUserAvatar } from '@/lib/tool';
import Link from 'next/link';
import classNames from 'classnames';
import { useTranslations } from 'use-intl';

export default function ChildReply({
  query,
  childReplyItem,
  childReplyIndex,
  parentReplyItem,
  parentReplyIndex,
  replyItem,
  replyIndex,
  commentItem,
  commentIndex,
  postData,
  metadata,
}: {
  query: UseInfiniteQueryResult<IPostCommentParentReply>;
  childReplyItem: IPostCommentChildReply;
  childReplyIndex: number;
  parentReplyItem: IPostCommentParentReply;
  parentReplyIndex: number;
  replyItem: IPostCommentReply;
  replyIndex: number;
  commentItem: IPostComment;
  commentIndex: number;
  postData: IPostClientDetails;
  metadata: TMetadata;
}) {
  const env = metadata.env;
  const userQuery = useUser(metadata);
  const [replyContent, setReplyContent] = useState('');
  const { show } = useToast();
  const t = useTranslations('PostIdPage');

  const createChildReplyMutation = useMutation(
    async (variables: TBody<ICreateChildReplyBody>) => {
      await createChildReply(variables);
      await query.refetch({ throwOnError: true });
    },
  );

  async function onClickPostReply() {
    if (!userQuery.data?.user) {
      show({
        title: t('notLoggedInPrompt'),
        content: <LoginReminderContent />,
      });
      return;
    }

    const _replyContent = replyContent.trim();
    if (!_replyContent) {
      show({
        type: 'DANGER',
        message: t('replyContentEmptyError'),
      });
      return;
    }

    const content = sanitizeHtml(_replyContent);
    if (!content) {
      show({
        type: 'DANGER',
        message: t('replyContentEmptyError'),
      });
      return;
    }

    try {
      const parentReplyId = parentReplyItem.reply.id;
      await createChildReplyMutation.mutateAsync({
        data: {
          parentReplyId,
          content,
        },
      });

      setReplyContent('');
      show({
        type: 'SUCCESS',
        message: t('replyCompleted'),
      });
    } catch (e) {
      createChildReplyMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChangeReplyContent(e: ChangeEvent<HTMLTextAreaElement>) {
    setReplyContent(e.target.value);
  }

  return (
    <div>
      <div className="hstack gap-4">
        <div style={{ width: 64, height: 64 }}>
          <Image
            className="rounded-circle"
            src={getUserAvatar(childReplyItem.user, metadata).smallAvatarUrl}
            alt={childReplyItem.user.alias}
            title={childReplyItem.user.alias}
            width={64}
            height={64}
            placeholder="blur"
            blurDataURL={env.APP_BLUR_DATA_URL}
            style={{
              maxWidth: '100%',
              objectFit: 'cover',
            }}
          />
        </div>

        <div className="vstack">
          <div className="mb-4">
            <div
              dangerouslySetInnerHTML={{
                __html: childReplyItem.reply.content ?? '',
              }}
            ></div>
          </div>

          <div>
            <Link
              href={`/users/${childReplyItem.user.id}`}
              className="text-decoration-none text-muted"
            >
              {childReplyItem.user.alias}
            </Link>
            {userQuery.data?.user ? (
              <a
                className="user-select-none text-muted text-decoration-none text-decoration-underline-hover mx-2"
                data-bs-toggle="collapse"
                href={`#yw-r-c-${childReplyItem.reply.id}`}
                role="button"
                aria-expanded="false"
                aria-controls={`yw-r-c-${childReplyItem.reply.id}`}
              >
                {t('reply')}
              </a>
            ) : (
              <span className="user-select-none text-muted mx-2">回复</span>
            )}
            <Link
              href={`/users/${parentReplyItem.user.id}`}
              className="text-muted text-decoration-none text-decoration-underline-hover"
            >
              {parentReplyItem.user.alias}
            </Link>
            &nbsp;·&nbsp;
            <span>
              <time
                className={classNames(
                  childReplyItem.reply._createdOnText ? false : 'invisible',
                )}
                dateTime={childReplyItem.reply.createdOn}
              >
                {childReplyItem.reply._createdOnText}
              </time>
            </span>
          </div>

          {userQuery.data?.user && (
            <div className="collapse" id={`yw-r-c-${childReplyItem.reply.id}`}>
              <div>
                <textarea
                  className="form-control my-3"
                  rows={4}
                  placeholder={t('enterReply')}
                  name="replyContent"
                  value={replyContent}
                  onChange={onChangeReplyContent}
                ></textarea>
                <button
                  disabled={createChildReplyMutation.isLoading || !replyContent}
                  onClick={onClickPostReply}
                  type="button"
                  className="btn btn-outline-primary my-3 w-100"
                >
                  {createChildReplyMutation.isLoading ? (
                    <span
                      className="spinner-border spinner-border-sm me-2"
                      role="status"
                      aria-hidden="true"
                    ></span>
                  ) : (
                    <i className="bi bi-cursor me-2"></i>
                  )}
                  {t('postReply')}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
